package com.xhwl.centiotdata.suppliersystem.younijia;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.xhwl.centiotdata.pojo.constant.YouNiJiaConstant;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.younijia.PedestrianRecordYouNiJiaDTO;
import com.xhwl.common.dto.cent.pedes.OpenDoorRecordDTO;
import com.xhwl.common.enums.DirectionEnum;
import com.xhwl.common.enums.SourceTypeEnum;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author msy
 */
@Slf4j
@Service
public class PedestrianYouNiJiaHandler {

//    @Value("${http-proxy.ip:-1}")
//    private String ip;
//    @Value("${http-proxy.port:-1}")
//    private Integer port;

    public List<PedestrianRecordYouNiJiaDTO> pullVisits(PedestrianIntegrationConfigDTO configDTO, Date date) {
        if(date == null){
            date = new Date();
        }
        //计算开始时间（拉取前1小时的数据）
        Date startTime = DateUtil.offset(date, DateField.HOUR_OF_DAY, -1);

        String host = configDTO.getIpAndPort();
        String token = configDTO.getToken();
        String url = host + YouNiJiaConstant.OPEN_RECORD;

        List<PedestrianRecordYouNiJiaDTO> pedestrianRecordYouNiJiaDTOList = new ArrayList<>();
        Integer pageNum = YouNiJiaConstant.PAGE_NUM;
        Integer pageSize = YouNiJiaConstant.PAGE_SIZE;
        Integer total;
        do {
            Map<String, Object> params = new HashMap<>();
            params.put("service_id", configDTO.getServiceId());
            params.put("pageNum", pageNum);
            params.put("pageSize", pageSize);
            params.put("startTime", DateUtil.formatDateTime(startTime));
            params.put("endTime", DateUtil.formatDateTime(date));
            params.put("token", token);

            HttpRequest httpRequest = HttpRequest.post(url).body(JSON.toJSONString(params));
//            if(!"-1".equals(ip) && !Integer.valueOf(-1).equals(port)) {
//                httpRequest.setHttpProxy(ip, port);
//            }
            String str = httpRequest.execute().body();
            JSONObject result = new JSONObject(str);
            JSONArray data = result.getJSONArray("data");
            total = result.getInt("Total");
            List<PedestrianRecordYouNiJiaDTO> add = JSON.parseArray(data.toString(), PedestrianRecordYouNiJiaDTO.class);
            pedestrianRecordYouNiJiaDTOList.addAll(add);
        } while ((pageSize * pageNum++) < total);

        return pedestrianRecordYouNiJiaDTOList;
    }


    /**
     * 转换数据
     * @param configDTO
     * @param recordYouNiJiaDTOList
     * @return
     */
    public List<OpenDoorRecordDTO> handleRecord(PedestrianIntegrationConfigDTO configDTO, List<PedestrianRecordYouNiJiaDTO> recordYouNiJiaDTOList) {
        if(ChkUtil.isNull(recordYouNiJiaDTOList)) {
            return new ArrayList<>();
        }

        List<OpenDoorRecordDTO> openDoorRecordDTOList = new ArrayList<>();
        for(PedestrianRecordYouNiJiaDTO item : recordYouNiJiaDTOList) {
            OpenDoorRecordDTO openDoorRecordDTO = new OpenDoorRecordDTO();
            openDoorRecordDTO.setProjectId(configDTO.getProjectId());
            openDoorRecordDTO.setProductId(configDTO.getProductId());
            // 优你家门禁只记录进门，不记录出门
            openDoorRecordDTO.setDirection(DirectionEnum.IN.getId());
            openDoorRecordDTO.setUserName(item.getCust_name());
            openDoorRecordDTO.setDeviceName(item.getDevice_name());
            openDoorRecordDTO.setArrivalTime(DateUtil.formatDateTime(new Date(item.getOpen_time())));
            openDoorRecordDTO.setCode(String.valueOf(item.getRecord_id()));
            if(item.getStatus() != null) {
                openDoorRecordDTO.setState((short) (item.getStatus().equals("成功") ? 1 : 0));
            }
            if(ChkUtil.isNotNull(item.getDirection())) {
                openDoorRecordDTO.setSourceType(item.getDirection().contains("业主") ? SourceTypeEnum.USER.getType() : SourceTypeEnum.VISITOR_USER.getType());
            }
            openDoorRecordDTOList.add(openDoorRecordDTO);
        }
        return openDoorRecordDTOList;
    }
}
